//
//  LBMComposeViewController.swift
//  微博
//
//  Created by 刘保满 on 16/5/28.
//  Copyright © 2016年 itheima. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

class LBMComposeViewController: UIViewController {
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        //视图显示时就让文本输入框成为第一响应者
        textView.becomeFirstResponder()
    }
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //设置背景 可以解决跳转时卡顿现象
        self.view.backgroundColor = UIColor.whiteColor()
        //设置UI
        setupUI()
        registerNotification()
        
    }
    
    //注册通知
    private func registerNotification() {
        //键盘位置发生改变时
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(LBMComposeViewController.keyboardChange(_:)), name: UIKeyboardWillChangeFrameNotification, object: nil)
        //插入表情
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(LBMComposeViewController.insertEmoticon(_:)), name: EmoticonBtnDidClickNotification, object: nil)
        

        
    }
    //键盘将要改变frame 调用的方法
    @objc private func keyboardChange(n: NSNotification) {
        //键盘改变frame,toolBar需要改变约束,并且添加动画
        //        print(n)
        
        //获取键盘显示的时间
        let time_t = (n.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        //键盘最后frame改变值
        let rect = (n.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        
        print(time_t,rect.origin.y)
        
        let offsetY = -(ScreenHeight - rect.origin.y)
        print(offsetY)
        UIView.animateWithDuration(time_t) {
            
            //这时要修改toolBar的约束
            self.toolBar.snp_updateConstraints(closure: { (make) in
                make.bottom.equalTo(offsetY)
            })
            //刷新视图
            self.view.layoutIfNeeded()
            
        }

    }
    //插入表情通知调用的方法

    @objc private func insertEmoticon(n: NSNotification) {
        
        guard let em = n.object as? LBMEmoticon else {
            return
        }
        
        //插入点击表情按钮
        textView.insertEmoticon(em)
        
        
    }


    //右侧发送按钮点击事件
    @objc private func send() {
        
        print("发送微博")
        LBMNetworkTools.sharedTools.sendStatus(textView.fullText(), images: pictureSelector.images) { (responsseObject, error) in
            if error != nil {
                SVProgressHUD.showErrorWithStatus("发布微博失败")
                return
            }
            
            SVProgressHUD.showSuccessWithStatus("发布微博成功")
            
        }
        
        
        
    }
    
    //实现底部工具条按钮的点击事件
    @objc private func selectPicture() {
        
        print("选择图片")
        //选择图片
        pictureSelector.view.snp_updateConstraints { (make) in
            
            make.height.equalTo(ScreenHeight / 3 * 2)
            
        }
        
        
    }
    
    //选择表情调用事件
    @objc private func selectEmoticon() {
        print("选择表情")
        //系统键盘出现的时候 imputView为nil
        textView.inputView = (textView.inputView == nil) ? keyboardView : nil
        
        textView.reloadInputViews()
 
    }
    
    
    
    
    
    //右侧按钮
    private lazy var rightBarButtonItem: UIBarButtonItem = {
        
        let btn = UIButton()
        
        btn.setTitle("发送", forState: .Normal)
        btn.titleLabel?.font = UIFont.systemFontOfSize(14)
        btn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        btn.setTitleColor(UIColor.darkGrayColor(), forState: .Disabled)
        btn.setBackgroundImage(UIImage(named: "common_button_orange"), forState: .Normal)
        
        btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)
        
        btn.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: .Highlighted)
        
        btn.addTarget(self, action: #selector(LBMComposeViewController.send), forControlEvents: .TouchUpInside)
        
        
        btn.frame =  CGRect(x: 0, y: 0, width: 45, height: 30)
        
        let barButtonItem = UIBarButtonItem(customView: btn)
        
        return barButtonItem
        
    }()
    //文本输入视图 改为自定义的
    private lazy var textView: LBMTextView = {
        let tv = LBMTextView()
        
        //        tv.text = "因何而生,因何而战"
        tv.backgroundColor = UIColor(white: 0.8, alpha: 1)
        tv.font = UIFont.systemFontOfSize(18)
        tv.textColor = UIColor.darkGrayColor()
        
        //设置滚动视图键盘消失
        tv.keyboardDismissMode = .OnDrag
        tv.alwaysBounceVertical = true
        tv.delegate = self
        return tv
    }()
    //占位文字
    private lazy var placeHolderLabel: UILabel = UILabel(title: "因何而战,因何而生", font: 18, textColor: UIColor.lightGrayColor())
    
    //底部工具条
    private lazy var toolBar: UIToolbar = UIToolbar()
    
    //添加控制器的属性
    //MARK: 图片选择
    private lazy var pictureSelector: LBMPictureSelectorController = LBMPictureSelectorController()
    
    //表情视图
    private lazy var keyboardView: LBMEmotionKeyboardView = LBMEmotionKeyboardView()
    

    
    //移除通知
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
        
    }
    
}


extension LBMComposeViewController {
    
    
    private func setupUI() {
        
        //设置导航栏
        setNavBar()
        setTextView()
        setSelectorVC()
        setToolBar()
    }
    
    
    private func setNavBar() {
        
        //设置左侧按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", target: self, action: #selector(LBMComposeViewController.closeDidClick))
        
        navigationItem.rightBarButtonItem = rightBarButtonItem
        //右侧按钮交互关闭
        navigationItem.rightBarButtonItem?.enabled = false
        
        let myView = UIView(frame: CGRect(x: 0, y: 0, width: 220, height: 40))
        
        let titleLabel = UILabel(title: "发布微博", font: 16, textColor: UIColor.darkGrayColor())
        
        let nameLabel = UILabel(title: LBMUserAccountViewModel.sharedAccountViewModel.userAccount?.name ?? "", font: 13, textColor: UIColor.lightGrayColor())
        
        //添加到父视图
        myView.addSubview(titleLabel)
        myView.addSubview(nameLabel)
        
        //设置约束
        titleLabel.snp_makeConstraints { (make) in
            
            make.centerX.equalTo(myView.snp_centerX)
            make.top.equalTo(myView.snp_top)
        }
        
        nameLabel.snp_makeConstraints { (make) in
            
            make.centerX.equalTo(myView.snp_centerX)
            make.bottom.equalTo(myView.snp_bottom)
            
        }
        
        navigationItem.titleView = myView
    }
    
    //导航栏左侧按钮点击事件
    @objc private func closeDidClick() {
        self.view.endEditing(true)
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //文本输入视图
    private func setTextView() {
        //添加到父视图
        self.view.addSubview(textView)
        //设置约束
        textView.snp_makeConstraints { (make) in
            
            make.top.left.right.equalTo(self.view)
            make.height.equalTo(ScreenHeight / 3)
        }
        
        //添加到文本输入视图
        textView.addSubview(placeHolderLabel)
        //设置约束
        placeHolderLabel.snp_makeConstraints { (make) in
            
            make.top.equalTo(textView.snp_top).offset(8)
            make.left.equalTo(textView.snp_left).offset(5)
            
        }
        
        
    }
    
    //底部工具条
    private func setToolBar() {
        //添加到父视图
        self.view.addSubview(toolBar)
        //设置约束
        toolBar.snp_makeConstraints { (make) in
            
            make.left.right.bottom.equalTo(self.view)
        }
        
        //设置工具条上的按钮
        var items = [UIBarButtonItem]()
        
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName": "selectPicture"],
                            ["imageName": "compose_mentionbutton_background","actionName": "selectPicture"],
                            ["imageName": "compose_trendbutton_background","actionName": "selectPicture"],
                            ["imageName": "compose_emoticonbutton_background", "actionName": "selectEmoticon"],
                            ["imageName": "compose_add_background","actionName": "selectPicture"]]
        
        for item in itemSettings {
            let imageName = item["imageName"]
            let action = item["actionName"]!
            
            //
            let item = UIBarButtonItem(imageName: imageName, title: nil, target: self, action: Selector(action))
            //添加到按钮数组
            items.append(item)
            //添加弹簧
            let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(space)
            
        }
        //移除最后一个多余的弹簧
        items.removeLast()
        toolBar.items = items
        
    }
    
    //底部选择图片视图
    private func setSelectorVC() {
        //添加子视图控制器,一定要加上这句话
        self.addChildViewController(pictureSelector)
        //使用控制器的视图
        self.view.addSubview(pictureSelector.view)
        
        //把toolBar移动到最前面
        self.view.bringSubviewToFront(toolBar)
        
        
        //设置约束
        pictureSelector.view.snp_makeConstraints { (make) in
            
            make.left.right.bottom.equalTo(self.view)
            make.height.equalTo(0)
            
        }
        
        
    }
    
    
}

//代理方法
extension LBMComposeViewController: UITextViewDelegate {
    
    func textViewDidChange(textView: UITextView) {
        
        //文本输入框发生改变时,让占位的label隐藏
        placeHolderLabel.hidden = textView.hasText()
        
        //让右侧的发送按钮可以点击
        rightBarButtonItem.enabled = textView.hasText()
        
    }
    
    
    
    
}







